import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

api.interceptors.request.use((config) => {
  const token = sessionStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `${token}`
  }
  return config
})

api.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code != 200) {
      if (res.code === 401) {
        window.location.href = '/401'
      }
      // 如果 205 身份认证失败，跳转登录
      if (res.code === 205) {
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            sessionStorage.clear() // 清除浏览器全部临时缓存
            window.location.href = '/login' // 去登录页
          })
          .catch(() => {})
      } else {
        ElMessage({
          message: res.message || 'Error',
          type: 'error',
          duration: 3 * 1000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  (error) => {
    if (error.response?.status === 401) {
      sessionStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default api
